#include "ui_player.h"
#include <stdio.h> 
#include "app_controller.h"
#include "player_controller.h"
#include <sys/time.h>
#include <sys/stat.h>
#include "service_favorites.h"
#include "service_player.h"
#include "ui_favorites.h"


// 全局变量定义
lv_obj_t *ui_player_screen;
lv_obj_t *ui_player_fav_btn;
lv_obj_t *ui_player_pause_btn;
lv_obj_t * ui_loading_spinner;
// 全局的加载检查定时器
lv_timer_t * g_loading_check_timer = NULL; 
//创建全局变量初始化定时器
lv_timer_t *g_initial_load_timer = NULL;
//创建全局的收藏视频的定时器
lv_timer_t *g_favorite_load_timer = NULL;
// 新增一个UI元素用于刷新成功提示 
lv_obj_t *ui_refresh_toast = NULL;

//创建一块幕布给收藏夹使用
lv_obj_t *ui_loading_curtain;

//声明收藏夹屏幕
extern lv_obj_t * ui_favorites_screen;


//检查加载函数申明
static void start_loading_checker(void);


// 定义一个函数来获取毫秒级的时间戳
static uint64_t get_current_time_ms(void) {
    struct timeval tv;
    gettimeofday(&tv, NULL);//获取当前时间
    return (uint64_t)tv.tv_sec * 1000 + (uint64_t)tv.tv_usec / 1000;
    //sec秒数（自1970年1月1日UTC时间起）计算1970年到现在的毫秒数
    //usec微秒级     两个相加获得当前时间戳
}


// 增加一个函数，用于根据收藏状态更新按钮样式
void update_favorite_button_status() {
    if (playlist.current_index < 0) return; 

    int slot = (playlist.head_index + playlist.current_index) % MAX_HISTORY_SIZE;
    const char* url = playlist.urls[slot];

    lv_obj_t *label = lv_obj_get_child(ui_player_fav_btn, 0);
    if (service_favorite_is_favorited(url)) {
        lv_label_set_text(label, "Faved!");
        lv_obj_set_style_bg_color(ui_player_fav_btn, lv_palette_main(LV_PALETTE_PINK), 0);
    } else {
        lv_label_set_text(label, "Fav");
        lv_obj_set_style_bg_color(ui_player_fav_btn, lv_color_white(), 0);
        // 明确地将文字颜色设置为黑色
        lv_obj_set_style_text_color(label, lv_color_black(), 0);
    }
}


// 一个统一的清理函数，用于退出任何加载状态
static void cleanup_all_loading_states() {
    printf("UI: 清理所有加载状态...\n");
    // 隐藏 Spinner
    if (ui_loading_spinner) lv_obj_add_flag(ui_loading_spinner, LV_OBJ_FLAG_HIDDEN);
    //隐藏幕布
    if (ui_loading_curtain) lv_obj_add_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN); // 隐藏幕布
    // 删除“下一个视频”检查定时器
    if (g_loading_check_timer) {
        lv_timer_del(g_loading_check_timer);
        g_loading_check_timer = NULL;
    }
    // 删除“初始/刷新”检查定时器
    if (g_initial_load_timer) {
        lv_timer_del(g_initial_load_timer);
        g_initial_load_timer = NULL;
    }
}


// 定时器回调函数用于显示并自动隐藏提示
static void hide_toast_timer_cb(lv_timer_t *timer) {
    if (ui_refresh_toast)
    {
        lv_obj_add_flag(ui_refresh_toast, LV_OBJ_FLAG_HIDDEN);
    }
    lv_timer_del(timer);
}


void show_refresh_toast() {
    if (ui_refresh_toast == NULL) {
        ui_refresh_toast = lv_label_create(ui_player_screen);
        lv_label_set_text(ui_refresh_toast, "Refreshed");
        // 设置样式... (白色文字，半透明黑色背景)
        lv_obj_set_style_bg_color(ui_refresh_toast, lv_color_black(), 0);
        lv_obj_set_style_bg_opa(ui_refresh_toast, LV_OPA_50, 0);
        lv_obj_set_style_text_color(ui_refresh_toast, lv_color_white(), 0);
        lv_obj_set_style_pad_all(ui_refresh_toast, 10, 0);
        lv_obj_set_style_radius(ui_refresh_toast, 5, 0);
        lv_obj_align(ui_refresh_toast, LV_ALIGN_CENTER, 0, 0); // 居中显示
    }
    
    lv_obj_clear_flag(ui_refresh_toast, LV_OBJ_FLAG_HIDDEN); // 显示
    
    // 创建一个一次性定时器，1.5秒后隐藏提示
    lv_timer_create(hide_toast_timer_cb, 1500, NULL);
}



// 用于“等待下一个视频”的通用定时器回调
static void next_video_check_timer_cb(lv_timer_t *timer) {
    printf("定时器检查：尝试切换到下一个视频...\n");
    
    // 【正确行为】直接调用 service_play_next()，它内部会检查文件
    if (service_play_next()) {
        // 如果返回 true，说明切换成功！
        printf("切换成功！清理加载状态。\n");
        cleanup_all_loading_states(); // 清理并删除自己
        lv_obj_invalidate(ui_player_screen);


        /* //恢复背景透明
    lv_obj_set_style_bg_opa(ui_player_screen, LV_OPA_TRANSP, 0);
    lv_obj_invalidate(ui_player_screen); */
    }
}

// 仅用于“程序启动时”的初始加载定时器回调
static void initial_load_timer_cb(lv_timer_t *timer)
{
    // 【正确行为】只检查初始视频
    if (service_player_is_initial_video_ready()) {
        printf("初始/刷新视频已就绪！\n");
        cleanup_all_loading_states(); // 清理并删除自己
        // 【正确行为】只播放初始视频
        service_player_play_initial_video();
        lv_obj_invalidate(ui_player_screen);


         /* //恢复背景透明
    lv_obj_set_style_bg_opa(ui_player_screen, LV_OPA_TRANSP, 0);
    lv_obj_invalidate(ui_player_screen); */
    }
}


// 用于等待收藏视频的定时器回调
static void favorite_load_timer_cb(lv_timer_t *timer) {
    if (service_player_is_favorite_video_ready()) {
        const char* url = (const char*)timer->user_data;
        cleanup_all_loading_states();
        // 调用新的播放函数
        service_player_play_favorite_video(url); 
        lv_obj_invalidate(ui_player_screen);
    }
}


// 一个暴露给 ui_favorites.c 的函数，用于启动这个流程
void start_favorite_loading_flow(const char* url) {
    cleanup_all_loading_states();
    printf("UI: 进入等待收藏视频加载状态...\n");
    if (ui_loading_curtain) lv_obj_clear_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN);
    if (ui_loading_spinner) lv_obj_clear_flag(ui_loading_spinner, LV_OBJ_FLAG_HIDDEN);
    
    // 创建定时器，并将URL作为用户数据传递过去
    g_favorite_load_timer = lv_timer_create(favorite_load_timer_cb, 200, (void*)url);
}


//启动定时器监测上滑播放下一个视频函数
static void start_loading_checker(void) {
    cleanup_all_loading_states(); // 启动前，先清理
    printf("UI: 进入上滑等待状态...\n");

    /* // 强制设置背景为黑色，覆盖任何残留颜色
    lv_obj_set_style_bg_color(ui_player_screen, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(ui_player_screen, LV_OPA_COVER, 0);
 */


if (ui_loading_curtain) lv_obj_clear_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN); // 显示幕布

    if (ui_loading_spinner) lv_obj_clear_flag(ui_loading_spinner, LV_OBJ_FLAG_HIDDEN);
    g_loading_check_timer = lv_timer_create(next_video_check_timer_cb, 200, NULL);
}


//创建定时器监测刷新和初始播放
static void start_initial_loading_flow() {
    cleanup_all_loading_states(); // 【关键】启动前，先清理
    printf("UI: 进入初始/刷新加载状态...\n");

    /* // 强制设置背景为黑色，覆盖任何残留颜色
    lv_obj_set_style_bg_color(ui_player_screen, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(ui_player_screen, LV_OPA_COVER, 0);
 */


    if (ui_loading_curtain) lv_obj_clear_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN); // 显示幕布


    if (ui_loading_spinner) lv_obj_clear_flag(ui_loading_spinner, LV_OBJ_FLAG_HIDDEN);
    g_initial_load_timer = lv_timer_create(initial_load_timer_cb, 200, NULL);
}


//滑动回调函数
static void gesture_event_cb(lv_event_t * e)
{
// 使用一个静态变量来记录上一次成功切换的时间
    static uint64_t last_swipe_time = 0;
    // 定义冷却时间为 1000 毫秒 (1秒)
    const int COOLDOWN_MS = 1000;

    uint64_t current_time = get_current_time_ms();
   // 如果距离上次滑动还不到1秒，则直接忽略本次事件
    if (current_time - last_swipe_time < COOLDOWN_MS) {
        return; // 还在冷却中，不做任何事
    }

    //从当前活跃的屏幕获取手势
    lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());

    bool switched = false; // 标记本次事件是否真的触发了切换
    if (dir == LV_DIR_TOP)
    {
        // 检查 service_play_next 的返回值
        if (service_play_next()) { // 如果成功切换

             cleanup_all_loading_states(); // 成功切换后，确保清理所有加载状态

             // 强制重绘整个UI
            lv_obj_invalidate(ui_player_screen);

            switched = true;
        } else { // 如果视频没准备好
            // 在显示加载标签前，先停止播放并清屏
            //直接撒是进程最粗暴简单
            
            
            // 重新触发一次预加载
            printf("视频未就绪，重新尝试预加载...\n");
            player_stop();
            preload_next_video();
            start_loading_checker(); // 只调用“上滑等待”流程
            
        }
    }
    else if(dir == LV_DIR_BOTTOM)
    {
        //接收下滑函数的返回值
        int retval = service_play_prev();
        if (retval == 1) { // 成功切换到上一个
            cleanup_all_loading_states();
            lv_obj_invalidate(ui_player_screen);
            switched = true;
        } 
        else if (retval == 2) 
        {   //已触发刷新
            
            // service_play_prev 内部调用了 player_stop
            start_initial_loading_flow(); // 启动定时器，等待刷新后的第一个视频
            show_refresh_toast(); // 显示“已刷新”提示
            switched = true;
        }


    }

     // 如果真的发生了切换，就更新时间戳
    if (switched) {
        last_swipe_time = current_time;
    }
    
}

// 按钮回调函数
static void pause_btn_event_cb(lv_event_t * e)
{
    //调用执行暂停函数
printf("__%d__\n",__LINE__);
    player_pause();

}




//收藏回调函数
static void fav_btn_event_cb(lv_event_t * e)
{
    printf("点击了收藏按钮\n");
    service_player_favorite_current_video();

    // 点击后，立刻更新按钮状态
    update_favorite_button_status();
}

// 回调函数打开收藏夹列表
static void open_favorites_cb(lv_event_t *e) {
    printf("点击了[打开收藏夹]按钮\n");
    ui_favorites_screen_create(); 
    player_stop();
    //清理屏幕
    //lv_obj_invalidate(ui_player_screen);
    if (ui_favorites_screen)
    {
        lv_scr_load(ui_favorites_screen); 
    }
    
}




// 初始化视频播放界面
void ui_player_screen_create(void)
{
    // 创建屏幕
    ui_player_screen = lv_obj_create(NULL);
    lv_obj_set_style_border_width(ui_player_screen, 0, LV_PART_MAIN);
    lv_obj_set_style_outline_width(ui_player_screen, 0, LV_PART_MAIN);
    
    lv_obj_set_style_bg_color(ui_player_screen,lv_color_hex(0x000000) , LV_PART_MAIN );

    lv_obj_set_style_bg_opa(ui_player_screen, LV_OPA_TRANSP, 0);
    lv_obj_clear_flag(ui_player_screen, LV_OBJ_FLAG_SCROLLABLE);



    // 2. 【关键】创建并配置黑色幕布
    ui_loading_curtain = lv_obj_create(ui_player_screen);
    lv_obj_remove_style_all(ui_loading_curtain); // 移除边框、半径等所有默认样式
    lv_obj_set_size(ui_loading_curtain, lv_pct(100), lv_pct(100)); // 尺寸占满全屏
    lv_obj_set_style_bg_color(ui_loading_curtain, lv_color_black(), 0);
    lv_obj_set_style_bg_opa(ui_loading_curtain, LV_OPA_COVER, 0); // 纯黑不透明
    lv_obj_align(ui_loading_curtain, LV_ALIGN_CENTER, 0, 0);


    // 创建加载圈 (Spinner)
    ui_loading_spinner = lv_spinner_create(ui_player_screen, 1000, 60);
    lv_obj_set_size(ui_loading_spinner, 100, 100);
    lv_obj_center(ui_loading_spinner);

 // 3.确保 spinner 在幕布的上层，这样才能看见它
    lv_obj_move_foreground(ui_loading_spinner);
    // 4. 【关键】默认隐藏幕布和加载圈，只有在需要时才显示
    lv_obj_add_flag(ui_loading_curtain, LV_OBJ_FLAG_HIDDEN);
    lv_obj_add_flag(ui_loading_spinner, LV_OBJ_FLAG_HIDDEN);

    lv_scr_load(ui_player_screen);

    // 创建右边栏容器
    lv_obj_t * sidebar = lv_obj_create(ui_player_screen);
    lv_obj_set_size(sidebar, 120, 300);
    lv_obj_align(sidebar, LV_ALIGN_RIGHT_MID, -20, 0);
    lv_obj_set_style_bg_color(sidebar, lv_color_hex(0xD3D3D3), LV_PART_MAIN);
    
lv_obj_set_style_bg_opa(sidebar, LV_OPA_50, LV_PART_MAIN);
    lv_obj_set_style_radius(sidebar, 15, LV_PART_MAIN);
    lv_obj_set_style_border_width(sidebar, 0, LV_PART_MAIN);

    // 设置Flex布局
    lv_obj_set_layout(sidebar, LV_LAYOUT_FLEX);
    lv_obj_set_flex_flow(sidebar, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(sidebar, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_SPACE_EVENLY);

    //  创建收藏按钮
    ui_player_fav_btn = lv_btn_create(sidebar);
    lv_obj_set_size(ui_player_fav_btn, 80, 80);
    lv_obj_add_event_cb(ui_player_fav_btn, fav_btn_event_cb, LV_EVENT_CLICKED, NULL);

    lv_obj_t *fav_label = lv_label_create(ui_player_fav_btn);
    lv_label_set_text(fav_label, "fav");
    lv_obj_center(fav_label);

     // 打开收藏夹列表 (List Button)
    lv_obj_t *list_btn = lv_btn_create(sidebar);
    lv_obj_set_size(list_btn, 80, 80);
    lv_obj_add_event_cb(list_btn, open_favorites_cb, LV_EVENT_CLICKED, NULL);

    lv_obj_t *list_label = lv_label_create(list_btn);
    lv_label_set_text(list_label, LV_SYMBOL_LIST); // 使用“列表”图标
    lv_obj_center(list_label);
     

    // 创建暂停按钮
    ui_player_pause_btn = lv_btn_create(sidebar);
    lv_obj_set_size(ui_player_pause_btn, 80, 80);
    lv_obj_add_event_cb(ui_player_pause_btn, pause_btn_event_cb, LV_EVENT_CLICKED, NULL);
    
    lv_obj_t *pause_label = lv_label_create(ui_player_pause_btn);
    lv_label_set_text(pause_label, LV_SYMBOL_PAUSE); // 使用“暂停”图标
    lv_label_set_text(pause_label, "pause");
    lv_obj_center(pause_label);



    // 为整个屏幕绑定滑动手势事件
    lv_obj_add_event_cb(ui_player_screen, gesture_event_cb, LV_EVENT_GESTURE, NULL);

    start_initial_loading_flow();

}